#include "PayBox.h"
#include <Arduino.h>

#include <SPI.h>
#include <TFT_eSPI.h>
#include <WiFi.h>

TFT_eSPI tft = TFT_eSPI();
char buf[32] = {0};
unsigned long lastMs = 0;

void showTimeTFT(const String &string) {
  tft.setTextColor(TFT_WHITE, TFT_BLACK);
  tft.drawCentreString(string, 160, 60, 7);
}

void showDateTFT(const String &string) {
  tft.setTextColor(TFT_CYAN, TFT_BLACK);
  tft.drawCentreString(string, 160, 150, 4);
}

void setup() {
  Serial.begin(115200);
  payTFTInit(tft, 16);
  payLEDInit();
  tft.println("Start Wifi Connect!");
  autoConfigWifi();
  tft.println("Wifi Connected!");
  sprintf(buf, "IP: %s", WiFi.localIP().toString().c_str());
  tft.println(buf);
  payNTPInit();
  setupOTAConfig();
  delay(2000);
  tft.fillScreen(TFT_BLACK);
  tft.setTextColor(TFT_WHITE, TFT_BLACK);
  tft.drawCentreString(buf, 160, 220, 2);
  // 重启按钮
  bindKeyEvent(PAY_KEY_ON, [] { ESP.restart(); });
}

void refreshTime() {
  boxNTPRefresh();
  auto h = TIME_NOW.hours, m = TIME_NOW.minutes;
  auto s = TIME_NOW.seconds, d = TIME_NOW.days;
  auto y = TIME_NOW.years;
  auto mon = TIME_NOW.months;
  if (s % 2 == 0) {
    sprintf(buf, "%02d:%02d:%02d", h, m, s);
  } else {
    sprintf(buf, "%02d %02d %02d", h, m, s);
  }
  showTimeTFT(buf);
  sprintf(buf, "%04d-%02d-%02d", y, mon, d);
  showDateTFT(buf);
}

void loop() {
  if (millis() - lastMs >= 1000) {
    lastMs = millis();
    auto led = random(0x010101, 0xffffff);
    payLEDShow(led);
    refreshTime();
    ArduinoOTA.handle();
  }
}